//
//  HXSitePictureViewController.m
//  KD
//
//  Created by 高得华 on 16/9/7.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXSitePictureViewController.h"
#import "HXQYPictureCollectionView.h"
#import "HXReportEvidenceViewController.h"
#import "Imitation_AlertView_TextField.h"
#import "HXUpDataImageModel.h"
#import "HXCreatePunishModel.h"

@interface HXSitePictureViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,Imitation_AlertView_TextFielddelegate,UIActionSheetDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *vcBgScrollView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *vcBgViewLayoutConstraintWidth;
@property (weak, nonatomic) IBOutlet UIView *vcBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *vcBgViewLayoutConstraint;

#pragma mark -----// 工地信息 \\-----
@property (weak, nonatomic) IBOutlet UIView *siteInformationBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *simBgViewlayoutConstraint;
//工地名称
@property (weak, nonatomic) IBOutlet UILabel *simSiteNameLabel;
//工地地址
@property (weak, nonatomic) IBOutlet UILabel *simSiteAddressLabel;
//创建时间
@property (weak, nonatomic) IBOutlet UILabel *simSiteCreateTimeLabel;
//检查人员
@property (weak, nonatomic) IBOutlet UITextField *simSiteInspectorsTF;
//任务描述
@property (weak, nonatomic) IBOutlet UITextView *simSiteTaskDescriptionTV;

#pragma mark -----// 签到定位 \\-------
@property (weak, nonatomic) IBOutlet UIView *signInBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *siBgViewLayoutConstraint;
//签到btn
@property (weak, nonatomic) IBOutlet UIButton *signInBtn;
//工地名称
@property (weak, nonatomic) IBOutlet UILabel *signInSiteNameLabel;
//签到地址
@property (weak, nonatomic) IBOutlet UILabel *signInSiteAddressLabel;
//签到时间
@property (weak, nonatomic) IBOutlet UILabel *signInSiteTimeLabel;

#pragma mark -----// 现场取证 \\-------
@property (weak, nonatomic) IBOutlet UIView *forensicInformationBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *fimBgViewlayoutConstraint;
//现场取证标题
@property (weak, nonatomic) IBOutlet UILabel *fimLabel;
//大图片
@property (weak, nonatomic) IBOutlet UIImageView *fimBigImgView;
//拍照按钮
@property (weak, nonatomic) IBOutlet UIButton *fimTakePicturesBtn;
//工地名称
@property (weak, nonatomic) IBOutlet UILabel *fimSiteNameLabel;
//工地地址
@property (weak, nonatomic) IBOutlet UILabel *fimSiteAddressLabel;
//拍照时间
@property (weak, nonatomic) IBOutlet UILabel *fimTaskPictureTimeLabel;
//发送时间
@property (weak, nonatomic) IBOutlet UILabel *fimSendTimeLabel;
//处理方式
@property (weak, nonatomic) IBOutlet UILabel *fimHandlingLabel;
//照片描述
@property (weak, nonatomic) IBOutlet UILabel *fimPictureNameLabel;
//小图片
@property (weak, nonatomic) IBOutlet HXQYPictureCollectionView *fimPictureCollectionView;
//@property (nonatomic,strong) HXQYPictureCollectionView * collectionView;//暂时图片
//发送按钮
@property (weak, nonatomic) IBOutlet UIButton *releaseBtn;

#warning ---------- 2016.9.7 --------

@property (nonatomic,assign) BOOL isAdd;
@property (nonatomic,assign) BOOL isListOrRiZhiPush;
@property (nonatomic,assign) BOOL isExist;//本地是否存在
@property (nonatomic,assign) BOOL isChange;
@property (nonatomic,strong) Imitation_AlertView_TextField * alertView;//模拟AlertView
@property (nonatomic,strong) NSData   * imageData;//照片的二进制文件
@property (nonatomic,copy)   NSString * takePhotoTime;//拍照时间
@property (nonatomic,copy)   NSString * fimPictureNameStr;//照片描述
@property (nonatomic,copy)   NSString * fimHandlingStr;//处罚方式
@property (nonatomic,copy)   NSString * siteName;//工地名称
@property (nonatomic,copy)   NSString * currentStr;//当前地址
@property (nonatomic,copy)   NSString * networkTime;//网络时间
@property (nonatomic,copy)   NSString * taskID;
@property (nonatomic,copy)   NSString * submitDate;//点击发送的时间

/**数据源*/
@property (nonatomic,strong) NSDictionary * localDataDic;//本地数据
/**现场取证*/
@property (nonatomic,strong) NSMutableDictionary * fimHandlingDictionary;//处罚类型的字典
@property (nonatomic,strong) NSMutableArray * fimHandlingDataArray;//现场取证的数据源数组

/**签到信息*/
@property (nonatomic,strong) NSMutableArray * signInDataArray;//签到信息的数据源数组

/**工地信息*/
@property (nonatomic,strong) NSMutableDictionary * siteInformationDictionary;//工地信息数据字典
@property (nonatomic,retain) NSMutableArray * siteInformationDataArray;//工地信息的数据源数组

/**下发整改时间选择器*/
@property (nonatomic,strong) UIAlertController *changePunishAlert;//整改时间弹窗视图
@property (nonatomic,strong) UIDatePicker * datePickerStart;
@property (nonatomic,strong) UIDatePicker * datePickerEnd;
@property (nonatomic,copy) NSString * startTimeSrt;//整改开始日期
@property (nonatomic,copy) NSString * endTimeStr;//整改结束日期

/**百度地图**/
@property (nonatomic,strong) BMKMapView * mapView;
@property (nonatomic,strong) BMKLocationService * location;
@property (nonatomic,assign) CLLocationCoordinate2D center;//中心点

@property (nonatomic,assign) NSInteger dataArrayCount;//数据源的个数
@property (nonatomic,assign) BOOL backLastViewIsUsed;//返回上一级需要存储数据嘛

@end

@implementation HXSitePictureViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    self.location.delegate = self;
    
    self.simBgViewlayoutConstraint.constant = 230;
    self.fimBgViewlayoutConstraint.constant = 536;
    self.vcBgViewLayoutConstraintWidth.constant = HXSCREEN_WIDTH;
    if (self.isListOrRiZhiPush) {
        self.siBgViewLayoutConstraint.constant  = -5;
        self.vcBgScrollView.contentSize = CGSizeMake(HXSCREEN_WIDTH, 856);
        self.vcBgViewLayoutConstraint.constant = 856;
        self.signInBtn.hidden = YES;
    }else{
        self.siBgViewLayoutConstraint.constant  = 144;
        self.vcBgScrollView.contentSize = CGSizeMake(HXSCREEN_WIDTH, 1000);
        self.vcBgViewLayoutConstraint.constant = 1000;
        self.signInBtn.hidden = NO;
    }
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    self.location.delegate = nil;
}

/**
 *初始化视图控制器
 *1. 需要 siteName:工地名称 2.需要 siteAddress 工地地址 3.content:任务描述
 *4.TaskID:任务ID 5.creteDate:创建时间 6.punishStyle:处罚类型 7.是否是增加的 isAdd
 *8.列表还是日志过来的:isListOrRiZhiPush
 */
+(instancetype)CreateSitePictureVCWithTaskID:(NSString *)taskID
                                   withIsAdd:(BOOL)isAdd
                       withIsListOrRiZhiPush:(BOOL)isListOrRiZhiPush
                           withIsExistTaskId:(BOOL)isExist
                            withLocalDataDic:(NSDictionary *)localDataDic{
    
    HXSitePictureViewController * sitePicVc = [[HXSitePictureViewController alloc] init];
    
    sitePicVc.taskID = taskID;
    sitePicVc.isAdd = isAdd;
    sitePicVc.isListOrRiZhiPush = isListOrRiZhiPush;
    sitePicVc.isExist = isExist;
    sitePicVc.localDataDic = localDataDic;
    
    //设置初始值
    sitePicVc.isChange      = YES;
    sitePicVc.imageData     = [NSData data];
    sitePicVc.takePhotoTime = @"";
    sitePicVc.fimPictureNameStr = @"";
    sitePicVc.fimHandlingStr = @"";
    sitePicVc.siteName = @"";
    sitePicVc.networkTime = @"";
    sitePicVc.startTimeSrt = @"";
    sitePicVc.endTimeStr = @"";
    sitePicVc.dataArrayCount = 0;
    sitePicVc.backLastViewIsUsed = NO;
    
    [[CCLocationManager shareLocation] getAddress:^(NSString *addressString) {
        sitePicVc.currentStr = addressString;
    }];
    
    return sitePicVc;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    dispatch_queue_t serialQueue=dispatch_queue_create("GetVCDatas", DISPATCH_QUEUE_SERIAL);//注意queue对象不是指针类型
    [SVProgressHUD showWithStatus:@"正在加载中,请稍后..."];
    //创建多个线程用于填充图片
    dispatch_async(serialQueue, ^{
        //获取网络时间
        [self loadCreateGetNetworkTime];
    });

    //设置页面布局
    [self loadCreateViewControllerLayout];
    
    if (self.isAdd || self.isExist){//添加及单元格存在时 不进行加载网络数据 否则进行加载网络
        //加载本地数据库
        [self loadGetLocalData];
    }else{
        //加载网络数据
        [self loadCreateGetDatas];
    }
}
/**
 * 百度地图定位
 */
-(void)loadBaiDuLocation{
    
    _mapView = [[BMKMapView alloc] init];
    [self location];
    
    [self.location startUserLocationService];
    self.mapView.showsUserLocation = NO;//先关闭显示的定位图层
    self.mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    self.mapView.showsUserLocation = YES;
    
}
//无网络或者 新添加的 或者 本地存在的就访问本地数据库
-(void)loadGetLocalData{
    if (self.isAdd) {
        HXTaskDescribeListModel * model = [[HXTaskDescribeListModel alloc] initWithDictionary:self.localDataDic error:nil];
        [self loadCreateShowSiteInformationViewWithModel:model];
    }else if (self.isExist) {
        
        if (self.localDataDic.count > 0) {
            
            //解析 签到及现场取证信息
            NSArray * reslutDict = [[self.localDataDic objectForKey:@"dict"] objectForKey:@"dict"];
            for (NSDictionary * dict in reslutDict) {
                HXJobPunishDetailsListModel * model = [[HXJobPunishDetailsListModel alloc] initWithDictionary:dict error:nil];
                if ([model.Con_PicType integerValue] == 1) {//签到信息
                    [self.signInDataArray addObject:model];
                    [self loadCreateShowViewControllerLayoutWithModel:model withCon_Pictype:[model.Con_PicType integerValue]];
                }else if ([model.Con_PicType integerValue] == 2){//现场取证信息
                    [self.fimHandlingDataArray addObject:model];
                }
            }
            if (self.fimHandlingDataArray.count > 0) {
                [self loadCreateShowViewControllerLayoutWithModel:self.fimHandlingDataArray[0] withCon_Pictype:2];
                self.fimPictureCollectionView.dataArray = self.fimHandlingDataArray;
            }
            
            //解析 工地信息
            HXTaskDescribeListModel * model = [[HXTaskDescribeListModel alloc] initWithDictionary:[self.localDataDic objectForKey:@"model"] error:nil];
            [self loadCreateShowSiteInformationViewWithModel:model];
            self.dataArrayCount += reslutDict.count;
        }
    }
}
/**
 * 加载数据
 */
- (void) loadCreateGetDatas {
    
    dispatch_queue_t serialQueue=dispatch_queue_create("GetVCDatas", DISPATCH_QUEUE_SERIAL);//注意queue对象不是指针类型
    //创建多个线程用于填充图片
    for (int i=0; i<3; ++i) {
        //异步执行队列任务
        dispatch_async(serialQueue, ^{
            [self loadCreateGetDatasWithGCD_ID:i];
        });
    }
    
    [NetworkAPI getPunishTypeSuccess:^(HXPunishTypeModel *result) {
        
        if ([result.code integerValue] == 200) {
            //处理处罚方式的数据源
            [self loadCreateChuLiDataArray:result.resultlist];
        }
        
    } failure:^(NSError *err) {
        
    }];
}
//异步加载数据
- (void)loadCreateGetDatasWithGCD_ID:(int)GCD_ID {
    switch (GCD_ID) {
        case 0://工地信息
        {
            [NetworkAPI getTaskDescribeWithTaskID:self.taskID
                                          Success:^(HXTaskDescribeModel *result) {
                                              if ([result.code integerValue] == 200) {
                                              
                                                  [self loadCreateShowSiteInformationViewWithModel:result.details];
                                              }
                                              
                                          } failure:^(NSError *err) {
                                          }];
        }
            break;
        case 1:
        {
            [NetworkAPI getJobPunishListWithTaskId:self.taskID
                                              type:@"1"
                                           success:^(HXJobPunishDetailsModel *result) {
                                               if ([result.code integerValue] == 200) {
                                                   [self.signInDataArray removeAllObjects];
                                                   [self.signInDataArray addObjectsFromArray:result.resultlist];
                                                   [self loadCreateShowViewControllerLayoutWithModel:result.resultlist[0] withCon_Pictype:1];
                                                   self.dataArrayCount += result.resultlist.count;
                                               }
                                           } failure:^(NSError *err) {
                                               
                                           }];
        }
            break;
        case 2:
        {
            [NetworkAPI getJobPunishListWithTaskId:self.taskID
                                              type:@"2"
                                           success:^(HXJobPunishDetailsModel *result) {
                                               if ([result.code integerValue] == 200) {
                                                   [SVProgressHUD dismiss];
                                                   for (NSInteger i = ([result.resultlist count] - 1); i >= 0 ; i--) {
                                                       [self.fimHandlingDataArray addObject:result.resultlist[i]];
                                                       if (i == [result.resultlist count] - 1) {
                                                           
                                                           [self loadCreateShowViewControllerLayoutWithModel:result.resultlist[i] withCon_Pictype:2];
                                                       }
                                                   }
                                                   self.fimPictureCollectionView.dataArray = self.fimHandlingDataArray;
                                                   self.dataArrayCount += result.resultlist.count;
                                               }else{
                                                   [SVProgressHUD dismiss];
                                               }
                                           } failure:^(NSError *err) {
                                               [SVProgressHUD dismiss];
                                           }];
        }
            break;
        default:
            break;
    }
}
/**
 * 处理处罚方式的数据源数组
 */
-(void)loadCreateChuLiDataArray:(NSArray *)punishArray{
    
    if (punishArray.count > 0) {
        [self.fimHandlingDictionary removeAllObjects];
        self.fimHandlingDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"与其他问题一并处罚",@"4", nil];
        for (HXPunishTypeListModel * listModel in punishArray) {
            [self.fimHandlingDictionary setObject:listModel.typeName forKey:listModel.typeValue];
        }
    }
}
/**
 * 设置页面布局
 */
- (void)loadCreateViewControllerLayout {
    self.navigationItem.title = @"现场检查";
    self.fimLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:24];
    //右侧的报告取证按钮
    //右侧导航栏的btn按钮
    if (!self.isListOrRiZhiPush) {
        UIBarButtonItem * rightBarBtn = [[UIBarButtonItem alloc] initWithTitle:@"报告取证"
                                                                         style:UIBarButtonItemStylePlain
                                                                        target:self
                                                                        action:@selector(rightBarBtnClick)];
        self.navigationItem.rightBarButtonItem = rightBarBtn;
    }
    
    //左侧按钮
    UIButton *leftBackBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftBackBtn setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    leftBackBtn.contentMode = UIViewContentModeLeft;
    leftBackBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    leftBackBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [leftBackBtn addTarget:self action:@selector(releaseBtnAct:) forControlEvents:UIControlEventTouchUpInside];
    leftBackBtn.frame=CGRectMake(0, 0,37,90);
    leftBackBtn.tag = 101;
    
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:leftBackBtn];
    
    //任务描述的边框
    self.simSiteTaskDescriptionTV.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.simSiteTaskDescriptionTV.layer.borderWidth = 0.5f;
    //设置检查人员的边框
    self.simSiteInspectorsTF.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.simSiteInspectorsTF.layer.borderWidth = 0.5f;
    
    //设置背景的圆角
    self.siteInformationBgView.layer.cornerRadius = 4.f;
    self.forensicInformationBgView.layer.cornerRadius = 4.f;
    self.signInBgView.layer.cornerRadius = 4.f;
    
    //创建 照片描述的弹框
    if (_alertView == nil) {
        
        _alertView = [[Imitation_AlertView_TextField alloc] initWithFatherViewFrameWidth:HXSCREEN_WIDTH withFrameHeight:HXSCREEN_HEIGHT];
        [_alertView viewHidden];
        _alertView.delegate = self;
        _alertView.title = @"照片描述";
    }
    
    //暂时图片的CollectionView
    //block  点击单元格返回 model数据
    [self.fimPictureCollectionView SelectReturnTapCell:^(HXJobPunishDetailsListModel *listModel) {
        
        [self loadCreateShowViewControllerLayoutWithModel:listModel withCon_Pictype:[listModel.Con_PicType integerValue]];
    }];
    
    //block  长按单元格返回 数据源数组 及 删除的坐标
    [self.fimPictureCollectionView ReturnDeleteDataArray:^(NSMutableArray<HXJobPunishDetailsListModel *> *modelDataArray, NSInteger firstIndex) {
        
        [self.fimHandlingDataArray removeAllObjects];
        self.fimHandlingDataArray = modelDataArray;
        self.fimPictureCollectionView.dataArray = modelDataArray;
        if (firstIndex == 0) {
            
            if (self.fimHandlingDataArray.count > 0) {
                
                [self loadCreateShowViewControllerLayoutWithModel:self.fimHandlingDataArray[firstIndex] withCon_Pictype:2];
            }else{
                
                [self loadCreateShowViewControllerLayoutWithModel:nil withCon_Pictype:2];
            }
            
        }else{
            
            [self loadCreateShowViewControllerLayoutWithModel:self.fimHandlingDataArray[firstIndex-1] withCon_Pictype:2];
        }
        
    }];
    
    NSDictionary * punishDic = @{@"1":@"口头警告",
                                 @"2":@"下发整改通知单",
                                 @"3":@"扣分处理",
                                 @"4":@"与其他问题一并处罚",
                                 @"5":@"停工",
                                 @"6":@"行政处罚",};
    self.fimHandlingDictionary = [NSMutableDictionary dictionaryWithDictionary:punishDic];
}
//进行签到
- (IBAction)sigInBtnAct:(id)sender {
    [self loadCreateGetNetworkTime];
    [self loadCreateDataDicWithPunishID:@"" withIsPunish:@"" withCon_Type:@"1"];
}
//进行拍照
- (IBAction)taskPictureBtnAct:(id)sender {
    UIAlertController * alertController=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * takePhotoBtn =[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
            picker.delegate = self;
            picker.allowsEditing = YES;//设置可 编辑
            picker.sourceType = sourceType;
            //            _isCarema = YES;
            [self presentViewController:picker animated:YES completion:^{
            }];//进入照相界面
        }
    }];
    UIAlertAction * cancelButton=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    
    [self presentViewController:alertController animated:YES completion:^{
    }];
    
    UIAlertAction * selectPicBtn = [UIAlertAction actionWithTitle:@"从相机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
        }
        pickerImage.delegate = self;
        pickerImage.allowsEditing = YES;
        [self presentViewController:pickerImage animated:YES completion:^{
        }];
        
    }];
    
    [alertController addAction:takePhotoBtn];
    [alertController addAction:selectPicBtn];
    [alertController addAction:cancelButton];
}
//进行发布
- (IBAction)releaseBtnAct:(UIButton *)sender {
    
    //    NSMutableDictionary * releaseDataDictionary = [NSMutableDictionary dictionary];
    //  1.存储工地信息数据
    //检查人员
    NSString * siteInspectors = self.simSiteInspectorsTF.text;
    NSString * siteTaskDescription = self.simSiteTaskDescriptionTV.text;
    [self.siteInformationDictionary setObject:siteInspectors.length <= 0 ? @"" : siteInspectors forKey:@"Task_GroupName"];
    [self.siteInformationDictionary setValue:siteTaskDescription.length <= 0 ? @"":siteTaskDescription forKey:@"Task_SiteWorkContent"];
    
    if (self.submitDate.length <= 0 || self.submitDate == nil) {
        self.submitDate = [GlobalUtil nowTimeDateFormatterWithNowTime:self.networkTime];
    }
    [self.siteInformationDictionary setObject:self.submitDate forKey:@"SubmitDate"];
    
    //    [releaseDataDictionary setObject:self.siteInformationDictionary forKey:@"model"];
    // 2.存储签到信息及现场取证信息数据
    NSMutableArray * sendDataArray = [NSMutableArray array];
    NSMutableArray * siAndFimArray = [NSMutableArray array];
    if (self.signInDataArray.count > 0) {//存储签到信息数据
        [siAndFimArray addObjectsFromArray:self.signInDataArray];
    }
    if (self.fimHandlingDataArray.count > 0) {
        [siAndFimArray addObjectsFromArray:self.fimHandlingDataArray];
    }
    //将 数据中的model数据转化为dictionary
    for (HXJobPunishDetailsListModel * model in siAndFimArray) {
        NSDictionary * dic = [self loadCreateModelTransferDictionaryWithModel:model];
        [sendDataArray addObject:dic];
    }
    NSDictionary * siAndFimDataDic = @{@"dict":sendDataArray};
    
    
    if (sender.tag == 100) {
        
        if (self.signInDataArray.count <= 0) {
            [LTAlertView showTitle:@"您还未进行定位签到，是否定位签到完成后，再次提交？" message:@"" ButtonTitles:@[@"直接提交",@"取消"] OnTapBlock:^(LTAlertView *alert, NSInteger num) {
                if (num == 0) {
                    [SVProgressHUD showWithStatus:@"正在上传数据，请稍后..."];
                    [self loadCreateUpDataWithDataDic:siAndFimDataDic];
                }
            }];
        }else{
            [SVProgressHUD showWithStatus:@"正在上传数据，请稍后..."];
            //上传数据
            [self loadCreateUpDataWithDataDic:siAndFimDataDic];
        }
    }else if (sender.tag == 101){
        
        if (self.dataArrayCount != sendDataArray.count || self.backLastViewIsUsed) {
            [LTAlertView showTitle:@"当前工地检查信息未保存,是否保存并退出?" message:@"" ButtonTitles:@[@"取消",@"保存并退出"] OnTapBlock:^(LTAlertView *alert, NSInteger num) {
                
                if (num == 1) {
                    [self loadCreateCunCuShuJuWithDic:siAndFimDataDic];
                }
                [self.navigationController popToViewController:[self.navigationController.childViewControllers objectAtIndex:1] animated:YES];
                
            }];
        }else{
            [self.navigationController popToViewController:[self.navigationController.childViewControllers objectAtIndex:1] animated:YES];
        }
    }
}

//上传数据
- (void)loadCreateUpDataWithDataDic:(NSDictionary *)dataDic{
    dispatch_queue_t serialQueue = dispatch_queue_create("UpData", DISPATCH_QUEUE_SERIAL);//注意queue对象不是指针类型
    //创建多个线程用于填充图片
    for (int i=0; i<2; ++i) {
        //异步执行队列任务
        dispatch_async(serialQueue, ^{
            [self loadCreateUpDataWithGCD_ID:i withDataDic:i == 0 ? nil : dataDic];
        });
    }
}
- (void)loadCreateUpDataWithGCD_ID:(int)GCD_ID withDataDic:(NSDictionary *)dataDic{
    if (GCD_ID == 0) {
        
        //1.修改小组人员、任务内容（一个工作日内）
        [NetworkAPI changePresonTaskContentWithTaskID:self.taskID
                                             SiteName:[self.siteInformationDictionary objectForKey:@"Task_SiteWorkContent"]
                                            GroupName:[self.siteInformationDictionary objectForKey:@"Task_GroupName"]
                                           SubmitDate:[self.siteInformationDictionary objectForKey:@"SubmitDate"]
                                              Success:^(HXBaseModel *result) {
                                                  if ([result.code isEqualToString:@"200"]) {
                                                  }
                                              } failure:^(NSError *err) {                                         }];
    }else if (GCD_ID == 1) {
        
        [NetworkAPI newCreateAddWithDic:dataDic
                                success:^(HXSendInformationModel *result) {
                                    if ([result.code integerValue] == 200) {
                                        [self tanchuangshitu];
                                        [self loadCreateDeleteLocalData];
                                        self.dataArrayCount = self.signInDataArray.count + self.fimHandlingDataArray.count;
                                        self.backLastViewIsUsed = NO;
                                    }else{
                                        [self loadCreateCunCuShuJuWithDic:dataDic];
                                        [self tanChuangViewWindow];
                                    }
                                }
                                failure:^(NSError * err) {
                                    [self loadCreateCunCuShuJuWithDic:dataDic];
                                    [self tanChuangViewWindow];
                                }];
    }
}

/**成功弹出提示*/
-(void)tanchuangshitu {
    [SVProgressHUD dismiss];
    [LTAlertView showTitle:@"提交成功,是否退出?" message:@"" ButtonTitles:@[@"取消",@"确定",] OnTapBlock:^(LTAlertView *alert, NSInteger num) {
        if(num == 1){
            //点击按钮之后 回调的bolck
            [self.navigationController popToViewController:self.navigationController.childViewControllers[1] animated:YES];
        }
    }];
}
/**
 不成功弹窗提示
 */
-(void)tanChuangViewWindow {
    [SVProgressHUD dismiss];
    [LTAlertView showTitle:@"提交失败,已保存本地,请网络良好时再次提交?" message:@"" ButtonTitles:@[@"确定",] OnTapBlock:^(LTAlertView *alert, NSInteger num) {
        //点击按钮之后 回调的bolck
        [self.navigationController popToViewController:self.navigationController.childViewControllers[1] animated:YES];
    }];
}
/**成功则删除数据*/
-(void)loadCreateDeleteLocalData{
    NSArray * taskIdArr = [HXSendPicModel MR_findByAttribute:@"taskId" withValue:self.taskID];
    //删除数据
    for (HXSendPicModel * model in taskIdArr) {
        BOOL isDelete = [model MR_deleteEntity];
        if (isDelete) {
            [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        }
    }
}

/**不成功存储到本地数据*/
-(void)loadCreateCunCuShuJuWithDic:(NSDictionary *)vcDic{
    [SVProgressHUD dismiss];
    //删除以前的数据
    [self loadCreateDeleteLocalData];
    
    if (self.isAdd) {
        
        NSDictionary * userInfo = @{@"taskId":self.taskID};
        [[NSNotificationCenter defaultCenter] postNotificationName:netWorkIsErrorNotificationGD object:nil userInfo:userInfo];
    }
    
    //存储数据时将 本页面的所有数据都存储 1.dict:代表照片 2.model:代表工地信息
    NSDictionary * dataDic = @{@"dict":vcDic,
                               @"model":self.siteInformationDictionary};
    /* 实体对象的创建保存与更新 */
    // 获取上下文环境
    NSManagedObjectContext *defaultContext = [NSManagedObjectContext MR_defaultContext];
    
    // 在当前上下文环境中创建一个新的 Person 对象.
    HXSendPicModel * picModel = [HXSendPicModel MR_createEntityInContext:defaultContext];
    HXSendPicContentModel * picContenModel = [HXSendPicContentModel MR_createEntityInContext:defaultContext];
    picContenModel.contentData = [NSJSONSerialization dataWithJSONObject:dataDic options:NSJSONWritingPrettyPrinted error:nil];
    picModel.taskId = self.taskID;
    picModel.contentModel = picContenModel;
    // 保存修改到当前上下文中.
    [defaultContext MR_saveToPersistentStoreAndWait];
}

//由Model --> Dictionary
-(NSDictionary *)loadCreateModelTransferDictionaryWithModel:(HXJobPunishDetailsListModel *)model{
    
    NSDictionary * dic = @{@"Con_UserID":[UserDefaultHandler getUserDetault:kID],
                           @"Con_Title":model.Con_Title,
                           @"Con_Content":model.Con_Content,
                           @"Con_Add":model.Con_Add,
                           @"Con_Date":model.Con_Date,
                           @"Con_Pic":model.Con_Pic == nil ? @"" : model.Con_Pic,
                           @"Con_TaskID":model.Con_TaskID,
                           @"Con_PicUrl":model.Con_PicUrl,
                           @"Con_PicType":model.Con_PicType,
                           @"Con_IsPunish":[model.Con_IsPunish isEqualToString:@"0"]?@"false":@"true",
                           @"Con_PunishID":model.Con_PunishID == nil ? @"" : model.Con_PunishID,
                           @"Con_PunishContent":model.Con_PunishContent == nil ? @"" : model.Con_PunishContent,
                           @"Con_IsSend":@"true",
//                           @"Con_SendDate":model.Con_SendDate,
                           @"Con_ChangeStart":model.Con_ChangeStart == nil ? @"" : model.Con_ChangeStart,
                           @"Con_ChangeEnd":model.Con_ChangeEnd == nil ? @"" : model.Con_ChangeEnd,
                           @"Img_Url":model.Img_Url,};
    
    if ([model.Img_Url isEqualToString:@"false"]) {
        self.backLastViewIsUsed = YES;
    }
    return dic;
}

#pragma mark //拍照信息\\
//设置并上传图片
-(void)setUpIconBtnWithImage:(UIImage *)image{
    
    self.takePhotoTime = [GlobalUtil getNowPhoneTime];
    //进行压缩照片
    self.imageData = UIImageJPEGRepresentation(image, 1);
    if  (self.imageData.length>300000){
        UIImage *image = [UIImage imageWithData:self.imageData];
        self.imageData = UIImageJPEGRepresentation(image, 0.005);
    }
    [_alertView viewShow];
}
//处罚方式
-(void)loadCreatePunishWay{
    
    CTActionSheet *actionSheet = [CTActionSheet actionSheetWithTitle:@"是否处罚"
                                                   cancelButtonTitle:@"取消"
                                              destructiveButtonTitle:@"处罚"
                                                   otherButtonTitles:@"不处罚" HandleBlock:^(int btnIndex) {
                                                       
                                                       switch (btnIndex) {
                                                           case 0:
                                                           {
                                                               UIActionSheet *sheet = [(UIActionSheet *)[UIActionSheet alloc] initWithTitle:@"处罚类型" delegate:self cancelButtonTitle:@"与其他问题一并处罚" destructiveButtonTitle:@"停工" otherButtonTitles:@"扣分处理",@"下发整改通知单",@"口头警告",@"行政处罚", nil];
                                                               
                                                               UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
                                                               if ([window.subviews containsObject:self.view]) {
                                                                   [sheet showInView:self.view];
                                                               } else {
                                                                   [sheet showInView:window];
                                                               }
                                                               
                                                           }
                                                               break;
                                                           case 1:
                                                           {
                                                               self.fimHandlingLabel.text = @"处罚方式:   暂不处罚";
                                                               //处罚方式
                                                               self.fimHandlingStr = @"暂不处罚";
                                                               [self loadCreateDataDicWithPunishID:@"" withIsPunish:@"0" withCon_Type:@"2"];
                                                               
                                                           }
                                                               break;
                                                           case 2:
                                                           {
                                                               self.fimHandlingLabel.text = @"处罚方式:";
                                                               //处罚方式
                                                               self.fimHandlingStr = @"";
                                                               [self loadCreateDataDicWithPunishID:@"" withIsPunish:@"0" withCon_Type:@"2"];
                                                           }
                                                               break;
                                                           default:
                                                               break;
                                                       }
                                                       
                                                   }];
    
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    if ([window.subviews containsObject:self.view]) {
        [actionSheet showInView:self.view];
    } else {
        [actionSheet showInView:window];
    }
}
//导航栏右侧按钮的点击相应事件
-(void)rightBarBtnClick {
    
    HXReportEvidenceViewController * vc = [[HXReportEvidenceViewController alloc] initWithAddress:self.currentStr withCon_Title:self.siteName withCon_TaskID:self.taskID];
    vc.type = SiteReportType;
    [self.navigationController pushViewController:vc animated:YES];
    
}
//获取网络时间
-(void)loadCreateGetNetworkTime{
    [NetworkAPI getServerDateSuccess:^(HXServerDateModel *result) {
        if ([result.code integerValue] == 200) {
            if (self.isExist || self.isAdd) {
                [SVProgressHUD dismiss];
            }
            self.networkTime = result.ServerDate;
        }else{
            if (self.isExist || self.isAdd) {
                [SVProgressHUD dismiss];
            }
            self.networkTime = [GlobalUtil getNowPhoneTime];//手机时间
        }
    } failure:^(NSError *err) {
        [SVProgressHUD dismiss];
        //[SVProgressHUD showErrorWithStatus:@"网络问题，请查看！"];
        self.networkTime = [GlobalUtil getNowPhoneTime];//手机时间
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ---// 存储数据 \\-----
-(void)loadCreateDataDicWithPunishID:(NSString *)punishID withIsPunish:(NSString *)IsPunish withCon_Type:(NSString *)con_type{
    
    HXJobPunishDetailsListModel * model;
    if ([con_type integerValue] == 2) {
        
        model = [[HXJobPunishDetailsListModel alloc]
                 initWithCon_TaskID:self.taskID//
                 withCon_Title:self.siteName//
                 withCon_Add:self.currentStr//
                 withCon_Content:self.fimPictureNameStr
                 withCon_Date:self.takePhotoTime//
                 withCon_PicUrl:[self.imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]
                 withCon_PicType:con_type//
                 withCon_IsPunish:IsPunish
                 withCon_Pic:con_type//
                 withCon_PunishID:[punishID integerValue] == 4 ? @"":punishID
                 withCon_IsSend:@"true"//
                 withCon_PunishContent:self.fimHandlingStr
                 withCon_ChangeStart:self.startTimeSrt
                 withCon_ChangeEnd:self.endTimeStr
                 withImg_Url:@"false"];
        
        [self.fimHandlingDataArray addObject:model];
        self.fimPictureCollectionView.dataArray = self.fimHandlingDataArray;
        
    }else if ([con_type integerValue] == 1){
       
        model = [[HXJobPunishDetailsListModel alloc]
                 initWithCon_TaskID:self.taskID//
                 withCon_Title:self.siteName//
                 withCon_Add:self.currentStr//
                 withCon_Content:@""
                 withCon_Date:self.networkTime//
                 withCon_PicUrl:@""
                 withCon_PicType:con_type//
                 withCon_IsPunish:@""
                 withCon_Pic:con_type//
                 withCon_PunishID:@""
                 withCon_IsSend:@"true"//
                 withCon_PunishContent:@""
                 withCon_ChangeStart:@""
                 withCon_ChangeEnd:@""
                 withImg_Url:@"false"];
        [self.signInDataArray removeAllObjects];
        [self.signInDataArray addObject:model];
    }
    
    [self loadCreateShowViewControllerLayoutWithModel:model withCon_Pictype:[model.Con_PicType integerValue]];
}
/**
 * 进行赋值 签到及现场取证
 */
-(void)loadCreateShowViewControllerLayoutWithModel:(HXJobPunishDetailsListModel *) model withCon_Pictype:(NSInteger)con_picType{
   
    if (con_picType == 2) {
        
        //图片
        if ([model.Img_Url isEqualToString:@"false"]) {
            
            self.fimBigImgView.image = [UIImage imageWithData:[NSData base64DataFromString:model.Con_PicUrl]];
        }else if ([model.Img_Url isEqualToString:@"true"]){
            [self.fimBigImgView sd_setImageWithURL:[NSURL URLWithString:model.Con_PicUrl] placeholderImage:[UIImage imageNamed:@"loading"]];
        }else{
            self.fimBigImgView.image = [[UIImage alloc] init];
        }
        
        //工地名称
        self.fimSiteNameLabel.text = [NSString stringWithFormat:@"工地名称: %@",model==nil?@"":model.Con_Title];
        //工地地址
        self.fimSiteAddressLabel.text = [NSString stringWithFormat:@"工地地址: %@",model==nil?@"":model.Con_Add];
        self.fimTaskPictureTimeLabel.text = [NSString stringWithFormat:@"拍照时间: %@",model==nil?@"":model.Con_Date];
        self.fimSendTimeLabel.text = [NSString stringWithFormat:@"发送时间: %@",model==nil?@"":model.Con_Date];
        //照片描述
        self.fimPictureNameLabel.text = [NSString stringWithFormat:@"照片描述: %@",model==nil?@"":model.Con_Content];
        //处罚方式
        if (model == nil) {
            self.fimHandlingLabel.text = @"处罚方式:";
        }else{
            if ([model.Con_PunishID integerValue] == 2) {
                self.fimHandlingLabel.text = [NSString stringWithFormat:@"处罚方式: %@ 整改开始日期:%@  整改结束日期:%@",model.Con_PunishContent,model.Con_ChangeStart,model.Con_ChangeEnd];
            }else{
                self.fimHandlingLabel.text = [NSString stringWithFormat:@"处罚方式: %@",model.Con_PunishContent];
            }
        }
    }else if (con_picType == 1){
        //工地名称
        self.signInSiteNameLabel.text = [NSString stringWithFormat:@"工地: %@",model.Con_Title];
        //工地地址
        self.signInSiteAddressLabel.text = [NSString stringWithFormat:@"地址: %@",model.Con_Add];
        //定位时间
        self.signInSiteTimeLabel.text = [NSString stringWithFormat:@"定位时间: %@",model.Con_Date];
    }
}

//工地信息进行赋值
- (void)loadCreateShowSiteInformationViewWithModel:(HXTaskDescribeListModel *)model {
    
    NSDictionary * siteDetaileDic =
    @{@"ID":model.ID,
      @"Task_WorkID":model.Task_WorkID,
      @"Task_WorkAPMGuid":model.Task_WorkAPMGuid,
      @"Task_SiteName":model.Task_SiteName,
      @"Task_SiteAdd":model.Task_SiteAdd,
      @"Task_SiteWorkContent":model.Task_SiteWorkContent,
      @"Task_DateTime":model.Task_DateTime,
      @"Task_UpDateTime":model.Task_UpDateTime,
      @"Task_X":model.Task_X,
      @"Task_Y":model.Task_Y,
      @"Task_KeyGuid":model.Task_KeyGuid,
      @"SubmitDate":model.SubmitDate == nil ? @"" : model.SubmitDate,
      @"Task_Type":model.Task_Type,
      @"Task_GroupName":model.Task_GroupName,};
    
    self.siteInformationDictionary = [NSMutableDictionary dictionaryWithDictionary:siteDetaileDic];
    
    self.siteName = model.Task_SiteName;
    
    //工地名称
    self.simSiteNameLabel.text = [NSString stringWithFormat:@"工地名称: %@",model.Task_SiteName];
    //工地名称
    self.simSiteAddressLabel.text = [NSString stringWithFormat:@"工地地址: %@",model.Task_SiteAdd];
    //工地名称
    self.simSiteCreateTimeLabel.text = [NSString stringWithFormat:@"开始时间: %@",model.Task_DateTime];
    //检查人员
    self.simSiteInspectorsTF.text = model.Task_GroupName;
    //任务描述
    self.simSiteTaskDescriptionTV.text = model.Task_SiteWorkContent;
    
    if (self.isListOrRiZhiPush) {
        self.isChange = NO;
    }else{
        
        if (!self.isAdd) {
            
            if (self.networkTime.length <= 0) {
                self.networkTime = [GlobalUtil getNowPhoneTime];
            }
            //进行判断是否可用
            if ([model.SubmitDate isEqualToString:@"0"] || [GlobalUtil compareDate:model.SubmitDate withDate:self.networkTime] == 1) {
                self.isChange = NO;
            }
            self.submitDate = model.SubmitDate;
        }else{
            self.submitDate = [GlobalUtil nowTimeDateFormatterWithNowTime:self.networkTime];
        }
    }
    
    [self loadCreateViewIsUsed];
}

//设置页面的状态是否可以使用
-(void)loadCreateViewIsUsed{
    self.fimPictureCollectionView.isUsed = self.isChange;
    self.releaseBtn.enabled = self.isChange;
    self.signInBtn.enabled = self.isChange;
    self.fimTakePicturesBtn.enabled = self.isChange;
    if (!self.isChange) {
        self.fimTakePicturesBtn.hidden = YES;
        self.releaseBtn.hidden = YES;
        [self.signInBtn setTitle:@"签到信息" forState:UIControlStateNormal];
        [self.signInBtn setBackgroundColor:[UIColor lightGrayColor]];
        self.simSiteInspectorsTF.enabled = NO;
        self.simSiteTaskDescriptionTV.editable = NO;
        if (self.isListOrRiZhiPush) {
            self.vcBgScrollView.contentSize = CGSizeMake(HXSCREEN_WIDTH, 816);
        }else{
            self.vcBgScrollView.contentSize = CGSizeMake(HXSCREEN_WIDTH, 940);
        }
    }
}

#pragma mark ---// 代理 \\-------
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
/**
 * Imitation_AlertView_TextFielddelegate
 */
- (void)at_textViewDidEndEditingWithView:(UIView *) alertView withTextView:(UITextView *)at_textView{
    
    //照片描述
    if (at_textView.text.length <= 0) {
        at_textView.text = @"";
    }
    self.fimPictureNameStr = at_textView.text;
    [self loadCreatePunishWay];
}

- (void)at_textViewDidViewHidden:(UIView *) alertView withTextView:(UITextView *)at_textView{
    
    //照片描述
    self.fimPictureNameStr = @"";
    //处罚方式
    [self loadCreatePunishWay];
}
/**
 * UIImagePickerControllerDelegate
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *originalImage =  (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
    
    if(!originalImage){
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    //拿到照片后
    [self setUpIconBtnWithImage:originalImage];
    //    self.backgroundImageView.image = originalImage;
    [picker dismissViewControllerAnimated:YES completion:nil];
}
/**
 * UIActionSheetDelegate
 */
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    NSString * punish = @"";
    
    switch (buttonIndex) {
        case 0:
            punish = @"5";//停工
            break;
        case 1:
            punish =@"3";//扣分处理
            break;
        case 2:
        {
            punish =@"2";//下发整改通知单
            
            //显示到屏幕上
            [self presentViewController:self.changePunishAlert animated:YES completion:^{
                
            }];
            
        }
            break;
        case 3:
            punish =@"1";//口头警告
            break;
        case 4:
            punish =@"6";//行政处罚
            break;
        case 5:
            punish =@"4";//与其他问题一并处罚
            break;
        default:
            break;
    }
    
    if ([punish integerValue] != 2) {
        
        self.fimHandlingStr = @"";
        
        //处罚方式
        self.fimHandlingStr = [self.fimHandlingDictionary objectForKey:punish];
        [self loadCreateDataDicWithPunishID:punish withIsPunish:@"1" withCon_Type:@"2"];
    }
}

#pragma mark ---// 懒加载 \\-------
-(UIAlertController *)changePunishAlert{
    
    if (_changePunishAlert == nil) {
        _changePunishAlert=[UIAlertController alertControllerWithTitle:@"下发整改时间" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        
        //在弹窗上添加输入框
        [_changePunishAlert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            //textField 就是添加的输入框
            textField.placeholder=@"整改开始时间";
        }];
        [_changePunishAlert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            textField.placeholder=@"整改结束时间";
        }];
        
        NSDate * dateNow = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd"];
        NSString * str= [dateFormatter stringFromDate:dateNow];
        _changePunishAlert.textFields[0].text = str;
        _changePunishAlert.textFields[1].text = str;
        _datePickerStart.datePickerMode = UIDatePickerModeDate;
        _datePickerEnd.datePickerMode = UIDatePickerModeDate;
        _changePunishAlert.textFields[0].inputView = self.datePickerStart;
        _changePunishAlert.textFields[1].inputView = self.datePickerEnd;
        
        UIAlertAction *cancelButton=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            //点击按钮之后 回调的bolck
            NSLog(@"取消");
            self.fimHandlingStr = @"";
            //处罚方式
            [self loadCreateDataDicWithPunishID:@"4" withIsPunish:@"1" withCon_Type:@"2"];
        }];
        
        UIAlertAction *cretainButtn=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            //点击按钮之后 回调的bolck
            //获得输入框的内容
            _startTimeSrt = _changePunishAlert.textFields[0].text;
            _endTimeStr = _changePunishAlert.textFields[1].text;
            
            self.fimHandlingStr = @"";
            //处罚方式
            self.fimHandlingStr = @"下发整改通知单";
            [self loadCreateDataDicWithPunishID:@"2" withIsPunish:@"1" withCon_Type:@"2"];
            
        }];
        
        //将按钮添加到弹窗上
        [_changePunishAlert addAction:cancelButton];
        [_changePunishAlert addAction:cretainButtn];
    }
    
    return _changePunishAlert;
}
-(UIDatePicker *)datePickerEnd{
    if (_datePickerEnd == nil) {
        
        _datePickerEnd = [[UIDatePicker alloc] init];
        _datePickerEnd.datePickerMode = UIDatePickerModeDate;
        NSDate * minDate = [NSDate date];
        _datePickerEnd.minimumDate = minDate;
        _datePickerEnd.tag = 1002;
        [_datePickerEnd addTarget:self action:@selector(datePickerChange:) forControlEvents:UIControlEventValueChanged];
    }
    
    return _datePickerEnd;
}
-(UIDatePicker *)datePickerStart{
    if (_datePickerStart == nil) {
        
        _datePickerStart = [[UIDatePicker alloc] init];
        _datePickerStart.datePickerMode = UIDatePickerModeDate;
        NSDate * minDate = [NSDate date];
        _datePickerStart.minimumDate = minDate;
        _datePickerStart.tag = 1001;
        [_datePickerStart addTarget:self action:@selector(datePickerChange:) forControlEvents:UIControlEventValueChanged];
        
    }
    
    return _datePickerStart;
}
/**
 * 时间选择器
 */
-(void)datePickerChange:(UIDatePicker *)datePicker {
    
    if (datePicker.tag == 1001) {
        NSDate * dateNow = _datePickerStart.date;
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd"];
        NSString * str= [dateFormatter stringFromDate:dateNow];
        //NSLog(@"时间一-------%@",str);
        self.changePunishAlert.textFields[0].text = str;
    }
    if (datePicker.tag == 1002) {
        NSDate * dateNow = _datePickerEnd.date;
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd"];
        NSString * str= [dateFormatter stringFromDate:dateNow];
        //NSLog(@"时间二-------%@",str);
        self.changePunishAlert.textFields[1].text = str;
    }
}
//数据源
-(NSMutableArray *)fimHandlingDataArray{
    if (_fimHandlingDataArray == nil) {
        
        _fimHandlingDataArray = [[NSMutableArray alloc] init];
    }
    
    return _fimHandlingDataArray;
}
-(NSMutableDictionary *)fimHandlingDictionary{
    if (_fimHandlingDictionary == nil) {
        _fimHandlingDictionary = [NSMutableDictionary dictionary];
    }
    return _fimHandlingDictionary;
}
-(NSMutableArray *)signInDataArray{
    if (_signInDataArray == nil) {
        _signInDataArray = [NSMutableArray array];
    }
    return _signInDataArray;
}
-(NSMutableDictionary *)siteInformationDictionary{
    if (_siteInformationDictionary == nil) {
        _siteInformationDictionary = [[NSMutableDictionary alloc] init];
    }
    return _siteInformationDictionary;
}
-(NSMutableArray *)siteInformationDataArray{
    if (_siteInformationDataArray == nil) {
        _siteInformationDataArray = [NSMutableArray array];
    }
    return _siteInformationDataArray;
}
-(BMKLocationService *)location{
    if (!_location) {
        _location = [[BMKLocationService alloc]init];
        _location.delegate = self;
        [_location startUserLocationService];
    }
    return _location;
}

/**
 * BMKLocationServiceDelegate
 */
//获得位置
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    self.center = userLocation.location.coordinate;
    BMKGeoCodeSearch *searcher =[[BMKGeoCodeSearch alloc]init];
    //发起反向地理编码检索
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    searcher.delegate = self;
    reverseGeoCodeSearchOption.reverseGeoPoint = _center;
    [searcher reverseGeoCode:reverseGeoCodeSearchOption];
}

/**
 *返回反地理编码搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结果
 *@param error 错误号，@see BMKSearchErrorCode
 */
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        self.currentStr = result.address;
        NSLog(@"定到位***********%@",self.currentStr);
    }else{
        
        [[CCLocationManager shareLocation] getAddress:^(NSString *addressString) {
            self.currentStr = addressString;
        }];
        
        NSLog(@"未定到位-------%@",self.currentStr);
    }
}

@end
